/*
 * DataSender.cpp
 *
 *  Created on: Jan 18, 2009
 *      Author: Andrzej Olchawa
 *      mailto: andrzejolchawa@gmail.com
 *      http://www.hardtechnology.org
 *      This is a part of the Armazd project, which is covered by
 *      GNU GPL v2 license.
 */

#include "DataSender.h"

DataSender::DataSender()
{
	hSocket = socket(AF_INET, SOCK_DGRAM, 0);
	if (hSocket < 0)
	{
		throw AgentException("DataSender(): can't create socket");
	}

	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
}

DataSender::~DataSender()
{
	if (hSocket >= 0)
	{
		shutdown(hSocket, SHUT_RDWR);
		close(hSocket);
	}
}

int DataSender::sendData(string data)
{
	if (listOfDestinations)
	{
		list<DestinationHost*>::iterator it;
		for (it=listOfDestinations->begin(); it!=listOfDestinations->end(); it++)
		{
			pServer = gethostbyname((*it)->getHost().c_str());
			memcpy(&addr.sin_addr.s_addr, pServer->h_addr, pServer->h_length);
			addr.sin_port = htons((*it)->getPort());
			int n = sendto(hSocket, data.c_str(), data.length(), 0, (sockaddr*)&addr, sizeof(addr));

			if (n <= 0)
			{
				throw AgentException("int DataSender.sendData: can't send data to: "
										+ string((*it)->getHost().c_str()) + ":"
										+ HTConverter::intToStr((*it)->getPort()));
			}
		}
		return 0;
	}
	return 1;
}
